#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

vector<vector<bool>> read_all_bits(const vector<string>& filenames) {
    vector<vector<bool>> all_bits;
    for (const auto& filename : filenames) {
        ifstream file(filename, ios::binary | ios::ate);
        if (!file.is_open()) {
            cerr << "Error opening file: " << filename << endl;
            all_bits.emplace_back(); // 添加空的vector
            continue;
        }
        streamsize size = file.tellg();
        file.seekg(0, ios::beg);
        vector<char> buffer(size);
        if (!file.read(buffer.data(), size)) {
            cerr << "Error reading file: " << filename << endl;
            all_bits.emplace_back();
            continue;
        }
        vector<bool> bits;
        for (char c : buffer) {
            for (int bit = 7; bit >= 0; --bit) { // 高位优先读取
                bits.push_back((c >> bit) & 1);
            }
        }
        all_bits.push_back(bits);
    }
    return all_bits;
}

int main(int argc,char* argv[]) {
    if(argc!=3)
{
    std::cerr<<"exe <input_dir> <output_file>\n";
    return 1;

}   
  std::string input_dir = argv[1];
  std::string output_file = argv[2];
    vector<string> filenames;
    for (int i = 1; i <= 128; ++i) {
        filenames.push_back(input_dir+"/"+to_string(i) + ".bin");
    }

    vector<vector<bool>> all_bits = read_all_bits(filenames);

    size_t max_bits = 0;
    for (const auto& bits : all_bits) {
        if (bits.size() > max_bits) {
            max_bits = bits.size();
        }
    }

    ofstream output(output_file, ios::binary);
    if (!output.is_open()) {
        cerr << "Error creating output file." << endl;
        return 1;
    }

    for (size_t i = 0; i < max_bits; ++i) {
        vector<bool> current_round_bits(128, false);
        for (size_t j = 0; j < filenames.size(); ++j) {
            if (i < all_bits[j].size()) {
                current_round_bits[j] = all_bits[j][i];
            }
        }

        // 将128位打包为16字节
        vector<char> bytes(16, 0);
        for (int byte_idx = 0; byte_idx < 16; ++byte_idx) {
            char byte = 0;
            for (int bit_idx = 0; bit_idx < 8; ++bit_idx) {
                int pos = byte_idx * 8 + bit_idx;
                if (pos >= 128) break;
                if (current_round_bits[pos]) {
                    byte |= (1 << (7 - bit_idx));
                }
            }
            bytes[byte_idx] = byte;
        }
        output.write(bytes.data(), bytes.size());
    }

    output.close();

    return 0;
}